import React,{useMemo} from "react";
import { useSelector } from "react-redux";
import { Link,useParams } from "react-router-dom";
import { createSelector } from '@reduxjs/toolkit';

import { selectUserById } from "../users/usersSlice";
import {
    //selectAllPosts,
    selectPostsByUser
} from "../posts/postsSlice";

import { useGetPostsQuery } from '../api/apiSlice'

const UserPage = () => {
    //const { userId } = match.params;

    const { userId } = useParams();

    const user = useSelector((state) => selectUserById(state, userId));

    //const posts = useSelector(selectAllPosts);
    //console.log('posts',posts)

    // const postsForUser = useSelector((state) => {
    //     const allPosts = selectAllPosts(state);
    //     console.log('allPosts',allPosts)
    //     return allPosts.filter((post) => post.user === userId);
    // });

    //const postsForUser = useSelector((state) => selectPostsByUser(state, userId));

    const selectPostsForUser = useMemo(()=>{
        // 返回此页面的唯一selector实例，以便过滤后的结果被正确的记忆
        return createSelector(
            (res) => res.data,
            (res,userId) => userId,
            (data,userId) => data?.filter((post)=> post.user === userId) ?? []
        )
    },[])

    //console.log('selectPostsForUser',selectPostsForUser)

    console.log('userId',userId)
    // query hooks 还使我们能够通过提供selectFromResult选项来选择缓存状态的片段，
    // 并且仅在所选片段更改时重新渲染
    const { postsForUser } = useGetPostsQuery(undefined,{
        selectFromResult: (result) => {
            console.log('result',result)
            return ({
                ...result,
                postsForUser: selectPostsForUser(result, userId),
            })
        }
    })
    console.log('postsForUser',postsForUser)

    const postTitles = postsForUser.map((post) => (
        <li key={post.id}>
            <Link to={`/posts/${post.id}`}>{post.title}</Link>
        </li>
    ));

    return (
        <section>
        <h2>{user.name}</h2>

        <ul>{postTitles}</ul>
        </section>
    );
};

export default UserPage;